import React, { PureComponent, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import {
  Card,
  Form,
  Button,
  Badge,
  Divider,
  Modal,
  Icon,
  Dropdown,
  Menu,
  Tag,
  Input,
  Row,
  Col,
  Select,
  message,
} from 'antd';

import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './DeviceList.less';
import OperationForm from '../../components/OperationForm';
import AdvancedForm from './AdvancedForm';
// const CreateForm = Form.create()(setBright);

const WrappedAdvancedSearchForm = Form.create({ name: 'advanced_search' })(AdvancedForm);
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['离线', '在线'];
const gpsStatus = ['No Sat', 'No Fix', '2D Fix', '3D Fix'];
const gpsstatusMap = ['error', 'default', 'success', 'processing'];
const ScreenStatus = ['关闭', '开启'];
const types = ['未绑定', '已绑定'];
const alarmstatus = ['无报警', '报警中'];
const alarmMap = ['default', 'error'];

@connect(({ dev, program, loading }) => ({
  dev,
  program,
  loading: loading.models.dev,
}))
export default class DeviceList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedRows: [],
      formValues: {},
      modalVisible: false,
      opType: 'init',
    };
  }

  componentDidMount() {
    const {
      dispatch,
      dev: { pagination },
    } = this.props;
    // console.log('dev pagination', pagination);
    this.devType = 'all';
    dispatch({
      type: 'dev/fetch',
      payload: { page: pagination.current, pageSize: pagination.pageSize, bindFlag: -1 },
    });
    dispatch({
      type: 'dev/fetchCompany',
    });
    dispatch({
      type: 'program/fetch',
      payload: { progAuditStatus: 1 },
    });
    dispatch({
      type: 'dev/fetchprog',
    });
    dispatch({
      type: 'dev/fetchCityCodes',
    });
    dispatch({
      type: 'dev/fetchUserCodes',
    });
    dispatch({
      type: 'dev/fetchOtaFile',
    });
    dispatch({
      type: 'dev/fetchOtaMode',
    });
  }
  onRef = ref => {
    this.child = ref;
  };
  onFresh = e => {
    // const {
    //   dispatch,
    //   dev: { pagination },
    // } = this.props;
    // const params = {
    //   page: pagination.current,
    //   pageSize: pagination.pageSize,
    // };

    // dispatch({
    //   type: 'dev/fetch',
    //   payload: params,
    // });
    this.child.handleSearch(e);
  };
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    dispatch({
      type: 'dev/fetch',
      payload: params,
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  handleMenuClick = key => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    // console.log('selectrows', selectedRows);
    if (selectedRows.length === 0) {
      message.error('请先勾选设备');
    } else {
      this.handleModalVisible(true, key);
    }
  };

  handleModalVisible = (flag, opType) => {
    // console.log('modal visible', flag, opType);
    this.setState({
      modalVisible: !!flag,
      opType,
    });
  };

  addDevice = () => {
    this.props.history.push(`/Dashboard/DevAdd`);
  };
  ClickDev = val => {
    //console.log('val', val);
    this.props.history.push(`/Dashboard/Monitor`, { state: { devId: val } });
  };
  delDev = () => {
    const { selectedRows } = this.state;
    if (selectedRows.length === 0) return;
    Modal.confirm({
      title: '确认删除',
      content: '确认要删除此设备吗？删除后不可恢复',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        const { dispatch } = this.props;

        dispatch({
          type: 'dev/remove',
          payload: {
            devIds: selectedRows,
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
      },
    });
  };
  onSearch = value => {
    const {
      dispatch,
      dev: { pagination },
    } = this.props;
    // console.log('dev pagination', pagination);
    this.setState({ formValues: value });
    dispatch({
      type: 'dev/fetch',
      payload: { page: 1, pageSize: pagination.pageSize, ...value },
    });
  };

  onExport = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'dev/onExport',
      payload: { ...value },
      callback: src => {
        const link = document.createElement('a');
        link.download = 'filename';
        link.style.display = 'none';
        link.href = src;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      },
    });
  };
  handleChange = value => {
    this.devType = value;
    this.onFresh();
  };
  render() {
    const { dev, loading, program } = this.props;

    //console.log('depprogramrogramv', program);
    const { selectedRows } = this.state;
    const columns = [
      {
        title: '设备ID',
        dataIndex: 'devId',
        sorter: true,
        width: 150,
        render: val => {
          return (
            <Link
              to={{
                pathname: `/dashboard/monitor`,
                state: { devId: val },
              }}
            >
              {val}
            </Link>
          );
        },
      },
      {
        title: '设备名称',
        dataIndex: 'devName',
        width: 200,
        sorter: true,
      },
      {
        title: '报警状态',
        dataIndex: 'alarmFlag',
        width: 150,
        render(val) {
          return <Badge status={alarmMap[val]} text={alarmstatus[val]} />;
        },
      },

      {
        title: 'sim卡号',
        dataIndex: 'simIccid',
        width: 150,
        sorter: true,
      },
      {
        title: '车牌',
        dataIndex: 'vehLicplateNo',
        width: 150,
      },
      {
        title: '车组',
        dataIndex: 'vehGroup',
        width: 150,
        sorter: true,
      },
      {
        title: '安装时间',
        dataIndex: 'devFixTime',
        width: 150,
        sorter: true,
      },
      {
        title: '在线状态',
        dataIndex: 'onOffline',
        width: 150,
        sorter: true,
        render(val) {
          return <Badge status={statusMap[val]} text={status[val]} />;
        },
      },
      {
        title: '最后上下线时间',
        dataIndex: 'lastOnOffTime',
        width: 250,
        sorter: true,
      },

      {
        title: '绑定状态',
        dataIndex: 'bindFlag',
        width: 150,
        render(val) {
          return <span>{types[val]}</span>;
        },
      },
      {
        title: '屏幕状态',
        width: 150,
        dataIndex: 'scrSwitch',
        render(val) {
          return <Badge status={ScreenStatus[val]} text={ScreenStatus[val]} />;
        },
      },
      {
        title: '屏幕分辨率',
        dataIndex: 'scrResolution',
        width: 250,
      },

      {
        title: '亮度',
        width: 150,
        dataIndex: 'brightness',
      },
      {
        title: 'sim卡是否在线',
        width: 150,
        dataIndex: 'simIsOnLine',
      },
      {
        title: 'sim卡状态',
        width: 150,
        dataIndex: 'simStatus',
      },
      {
        title: '传感器',
        width: 150,
        dataIndex: 'sensor',
      },
      {
        title: 'GPS状态',
        width: 150,
        dataIndex: 'gpsStatus',
        sorter: true,
        render(val) {
          return <Badge status={gpsstatusMap[val]} text={gpsStatus[val]} />;
        },
      },
      {
        title: '经纬度',
        width: 150,
        dataIndex: 'gpsPos',
        render(val) {
          return (
            <p>
              {val.lat}
              <br />
              {val.lng}
            </p>
          );
        },
      },
      {
        title: '正在播放节目',
        width: 150,
        dataIndex: 'lastPubProgName',
      },
      {
        title: '通信版本',
        width: 150,
        dataIndex: 'connVer',
      },
      {
        title: 'FPGA版本',
        width: 150,
        dataIndex: 'fpgaVer',
      },

      {
        title: 'WIFI/USB状态',
        width: 150,
        dataIndex: 'wuSwitch',
        render(val) {
          return <Badge status={statusMap[val]} text={ScreenStatus[val]} />;
        },
      },
      {
        title: '播放器版本',
        width: 150,
        dataIndex: 'playerVer',
      },
      {
        title: '系统版本',
        width: 150,
        dataIndex: 'cardSysVer',
      },
      {
        title: '速度（KM/H）',
        width: 150,
        dataIndex: 'speed',
      },
      {
        title: '模式',
        width: 150,
        dataIndex: 'module',
      },
      {
        title: '信号强度（dBm）',
        width: 150,
        dataIndex: 'signal',
      },
      {
        title: '备注',
        width: 150,
        dataIndex: 'remark',
      },
      {
        title: '操作',
        width: 150,
        fixed: 'right',
        render: (text, record, index) => (
          <Fragment>
            <Link
              to={{
                pathname: `/dashboard/devdetail/${record.devId}`,
                record,
              }}
            >
              详情
            </Link>
            <Divider type="vertical" />
            <Link
              to={{
                pathname: `/dashboard/devedit/${record.devId}`,
                record,
              }}
            >
              编辑
            </Link>
            <Divider type="vertical" />
            <Link
              to={{
                pathname: `/dashboard/devtask/${record.devName}`,
                record,
              }}
            >
              管理
            </Link>
            <Divider type="vertical" />
            <Link
              to={{
                pathname: `/dashboard/devtrack/${record.devId}`,
                record,
              }}
            >
              轨迹
            </Link>
            <Divider type="vertical" />
            <Link
              to={{
                pathname: `/dashboard/devtrackbaidu/${record.devId}`,
                record,
              }}
            >
              百度轨迹
            </Link>
          </Fragment>
        ),
      },
    ];
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="setBright">设置亮度</Menu.Item>
        <Menu.Item key="setPower">设置屏幕开关</Menu.Item>
        <Menu.Item key="setParams">设置通信参数</Menu.Item>
        <Menu.Item key="setPublish">发布节目</Menu.Item>
        <Menu.Item key="setReboot">设备重启</Menu.Item>
        <Menu.Item key="setWIFI">设置WIFI/USB</Menu.Item>
        <Menu.Item key="queryHwInfo">查询设备硬件信息</Menu.Item>
        <Menu.Item key="queryAlarm">查询报警</Menu.Item>
        <Menu.Item key="setAlarm">取消报警</Menu.Item>
      </Menu>
    );
    const extraData = (
      <div>
        <Tag style={{ fontSize: 15 }}>
          当前记录数:{' '}
          <span style={{ color: '#000000', fontWeight: 'bold', margin: 3 }}>{dev.total}</span>台
        </Tag>
        <Tag style={{ fontSize: 15 }}>
          设备总数:{' '}
          <span style={{ color: '#000000', fontWeight: 'bold', margin: 3 }}>{dev.devNum}</span>台
        </Tag>
        <Tag style={{ fontSize: 15 }}>
          在线设备:
          <span style={{ color: '#0a7829', fontWeight: 'bold', margin: 3 }}>{dev.onDevNum}</span>台
        </Tag>
      </div>
    );
    return (
      <PageHeaderLayout>
        <Card bordered={false} title="设备列表" extra={extraData} style={{ padding: 10 }}>
          {/* <div className={styles.tableListForm}>{this.renderForm()}</div> */}

          <WrappedAdvancedSearchForm
            onSearch={this.onSearch}
            program={dev.proglist}
            city={dev.cityCodes}
            onExport={this.onExport}
            onRef={this.onRef}
          />
          <Row gutter={24} style={{ marginTop: 10, marginBottom: 10 }}>
            <Col span={2}>
              <Button
                className={styles.actionButton}
                onClick={() => this.handleMenuClick('setBright')}
              >
                <Icon type="bulb" theme="twoTone" style={{ fontSize: '30px', color: '#08c' }} />
                <p>屏幕亮度</p>
              </Button>
            </Col>
            <Col span={2}>
              <Button
                className={styles.actionButton}
                onClick={() => this.handleMenuClick('setPower')}
              >
                <Icon type="switcher" theme="twoTone" style={{ fontSize: '30px', color: '#08c' }} />
                <p>屏幕开关</p>
              </Button>
            </Col>
            <Col span={2}>
              <Button
                className={styles.actionButton}
                onClick={() => this.handleMenuClick('setParams')}
              >
                <Icon type="sliders" theme="twoTone" style={{ fontSize: '30px', color: '#08c' }} />
                <p>通信参数</p>
              </Button>
            </Col>
            <Col span={2}>
              <Button
                className={styles.actionButton}
                onClick={() => this.handleMenuClick('setPublish')}
              >
                <Icon type="book" theme="twoTone" style={{ fontSize: '30px', color: '#08c' }} />
                <p>发布节目</p>
              </Button>
            </Col>
            <Col span={2}>
              <Button
                className={styles.actionButton}
                onClick={() => this.handleMenuClick('setReboot')}
              >
                <Icon type="rest" theme="twoTone" style={{ fontSize: '30px', color: '#08c' }} />
                <p>设备重启</p>
              </Button>
            </Col>
            <Col span={2}>
              <Button
                className={styles.actionButton}
                onClick={() => this.handleMenuClick('setWIFI')}
              >
                <Icon type="api" theme="twoTone" style={{ fontSize: '30px', color: '#08c' }} />
                <p>设置WIFI</p>
              </Button>
            </Col>
            <Col span={2}>
              <Button
                className={styles.actionButton}
                onClick={() => this.handleMenuClick('queryHwInfo')}
              >
                <Icon
                  type="dashboard"
                  theme="twoTone"
                  style={{ fontSize: '30px', color: '#08c' }}
                />
                <p>查询硬件</p>
              </Button>
            </Col>
            {/* <Col span={2}>
              <Button
                className={styles.actionButton}
                onClick={() => this.handleMenuClick('queryAlarm')}
              >
                <Icon type="alert" theme="twoTone" style={{ fontSize: '30px', color: '#08c' }} />
                <p>查询报警</p>
              </Button>
            </Col> */}
            <Col span={2}>
              <Button
                className={styles.actionButton}
                onClick={() => this.handleMenuClick('setAlarm')}
              >
                <Icon type="stop" theme="twoTone" style={{ fontSize: '30px', color: '#08c' }} />
                <p>取消报警</p>
              </Button>
            </Col>
            <Col span={2}>
              <Button
                className={styles.actionButton}
                onClick={() => this.handleModalVisible(true, 'oneKeyStart')}
              >
                <Icon
                  type="plus-circle"
                  theme="twoTone"
                  style={{ fontSize: '30px', color: '#08c' }}
                />
                <p>一键开屏</p>
              </Button>
            </Col>
            <Col span={2}>
              <Button
                className={styles.actionButton}
                onClick={() => this.handleModalVisible(true, 'oneKeyPubLishApply')}
              >
                <Icon
                  type="play-circle"
                  theme="twoTone"
                  style={{ fontSize: '30px', color: '#08c' }}
                />
                <p>一键发布</p>
              </Button>
            </Col>
            <Col span={2}>
              <Button
                className={styles.actionButton}
                onClick={() => this.handleModalVisible(true, 'devOta')}
              >
                <Icon
                  type="thunderbolt"
                  theme="twoTone"
                  style={{ fontSize: '30px', color: '#08c' }}
                />
                <p>OTA升级</p>
              </Button>
            </Col>
            <Col span={2}>
              <Button
                className={styles.actionButton}
                onClick={() => this.handleModalVisible(true, 'devUninstall')}
              >
                <Icon
                  type="delete"
                  theme="twoTone"
                  style={{ fontSize: '30px', color: '#08c' }}
                />
                <p>软件卸载</p>
              </Button>
            </Col>
          </Row>

          {/* <Row className={styles.tableListOperator} style={{ marginTop: 10, marginBottom: 10 }}>
            <Col span={12}>
              <Dropdown overlay={menu} style={{ marginRight: 10 }}>
                <Button type="primary" style={{ marginRight: 10 }}>
                  操作 <Icon type="down" />
                </Button>
              </Dropdown>
              <Button type="primary" onClick={() => this.addDevice()} style={{ marginRight: 10 }}>
                新建
              </Button>
              <Button type="primary" onClick={this.delDev} style={{ marginRight: 10 }}>
                删除
              </Button>
              <Button type="primary" onClick={this.onFresh} style={{ marginRight: 10 }}>
                刷新
              </Button>
              <Button
                type="primary"
                onClick={() => this.handleModalVisible(true, 'oneKeyStart')}
                style={{ marginRight: 10 }}
              >
                一键开关屏
              </Button>
              <Button
                type="primary"
                onClick={() => this.handleModalVisible(true, 'oneKeyPubLishApply')}
                style={{ marginRight: 10 }}
              >
                一键发布申请
              </Button>

              <Button
                type="primary"
                onClick={() => this.handleModalVisible(true, 'oneKeyPubLish')}
                style={{ marginRight: 10 }}
              >
                一键发布
              </Button>
            </Col>
          </Row> */}

          <StandardTable
            rowKey="devId"
            selectedRows={selectedRows}
            loading={loading}
            data={dev}
            columns={columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
            scroll={{ x: 3000 }}
          />
        </Card>
        <OperationForm
          selectedRows={this.state.selectedRows}
          handleModalVisible={this.handleModalVisible}
          modalVisible={this.state.modalVisible}
          dispatch={this.props.dispatch}
          opType={this.state.opType}
          program={this.props.program}
          history={this.props.history}
          company={dev.companyIdCodes}
          otaFile={dev.otaFile}
          otaMode={dev.otaMode}
          city={dev.cityCodes}
          userCodes={dev.UserCodes}
        />
      </PageHeaderLayout>
    );
  }
}
